import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_collection_app/utils/LogUtil.dart';
import 'package:material_collection_app/utils/dio_utils.dart';
import 'package:material_collection_app/widget/common/top_bar.dart';
import 'package:material_collection_app/widget/common/refresh.dart';
import 'package:material_collection_app/widget/enter/son_material_dialog.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:material_collection_app/widget/enter/son_material_action_dialog.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:material_collection_app/widget/common/empty_tips.dart';
import '../utils/utils.dart';

// 定义一个类继承于状态组件
class SonMaterialPage extends StatefulWidget {
  final Map arguments;

  SonMaterialPage({Key key, this.arguments}) : super(key: key);

  @override // 实例化
  State<StatefulWidget> createState() => MyMaterial();
}

class MyMaterial extends State<SonMaterialPage> {
  // 刷新
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  ScrollController listController = new ScrollController();
  // 变量定义
  var lastPage = 0;
  var currentPage = 1;
  int per_page = 20;
  var total = 0;
  int parentNum = 0;
  int d_num = 0;
  int y_num = 0;
  String baseApi = 'EnterMaterialSon/';
  int itemIndex = -1;

  // 子物资列表
  List sonList = [];
  // 物资选择数组
  List selectList = [];
  // 是否全选
  bool isSelectedAll = false;
  ItemDataSource _items = ItemDataSource([]);

  @override
  void initState() {
    super.initState();

    getList(isInit: true);
  }

  _cancelLoading() {
    Utils.showText(text: '获取成功');
    EasyLoading.dismiss();
  }

  _confrimData() {
    int id = widget.arguments['item']['id'];
    DioUtils.request('EnterMaterialSon/verification',
        context: context,
        method: "POST",
        params: {
          'enter_material_id': id,
        }, onSuccess: (res) {
      Utils.showText(text: res["msg"]);
    }, onError: (error) {});
  }

  // 获取子物资列表
  getList({bool loadMore = false, bool isInit = false}) {
    int id = widget.arguments['item']['id'];

    if (isInit == true) {
      setState(() {
        sonList = [];
        currentPage = 1;
      });

      // showDialog(
      //   context: context,
      //   barrierDismissible: false,
      //   builder: (_) {
      //     return new NetLoadingDialog(
      //       requestCallBack: _register(),
      //       outsideDismiss: false,

      //     );
      // //   });
      EasyLoading.show(status: '获取物资数据中...');
    }

    DioUtils.request('EnterMaterialSon/getList',
        context: context,
        method: "POST",
        params: {
          'current_page': currentPage,
          'page_size': 20,
          'enter_material_id': id,
        }, onSuccess: (res) {
      if (res['code'] == 1) {
        setState(() {
          d_num = res['data']['d_num'];
          y_num = res['data']['y_num'];
          parentNum = res['data']['num'];
          // sonList = res['data']['list']['data'];
          // sonList.forEach((element) {
          //   element['selected'] = false;
          //   //
          // });
          // print(sonList);
        });

        currentPage = res['data']['list']['current_page'];
        lastPage = res['data']['list']['last_page'];
        // per_page = res['data']['list']['per_page'];
        total = res['data']['list']['total'];
        var list = res['data']['list']['data'];
        list.forEach((element) {
          element['selected'] = false;
          element['num'] = element['num'];
        });
        if (lastPage > currentPage) {
          setState(() {
            currentPage = currentPage + 1;
            sonList.addAll(list);
          });
          getList();
        } else {
          setState(() {
            sonList.addAll(list);
          });
        }

        if (lastPage == currentPage || total == 0) {
          //  _register();
          _cancelLoading();
        }
      } else {
        _cancelLoading();
      }
    }, onError: (error) {
      _cancelLoading();
    });
  }

  // 创建按钮组件
  Widget _buildTopButtons() {
    return Column(
      children: <Widget>[
        Align(
          child: Container(
            height: 50,
            color: Utils.hexToColor('#297CFF'),
            padding: EdgeInsets.symmetric(horizontal: 10),
            // margin: EdgeInsets.only(bottom: 30.w),
            child: Row(
              children: [
                _buildTopButton(
                    '添加',
                    'add',
                    Alignment.centerLeft,
                    BorderRadius.horizontal(left: Radius.circular(30)),
                    '#33CCFF'),
                _buildTopButton(
                    '删除',
                    'del',
                    Alignment.centerLeft,
                    BorderRadius.horizontal(left: Radius.circular(30)),
                    '#990000'),
                _buildTopButton(
                    '修改备注',
                    'remark',
                    Alignment.centerLeft,
                    BorderRadius.horizontal(left: Radius.circular(30)),
                    '#66CC99'),
                _buildTopButton(
                    '修改数量',
                    'num',
                    Alignment.centerLeft,
                    BorderRadius.horizontal(left: Radius.circular(30)),
                    '#33CC66'),
                _buildTopButton(
                    '确认',
                    'confrim',
                    Alignment.centerLeft,
                    BorderRadius.horizontal(left: Radius.circular(30)),
                    '#FF9232')
              ],
            ),
          ),
        ),
        Container(
          padding: EdgeInsets.all(10),
          child: Text(
            "主物资数量: ${parentNum} 已分配数量: ${y_num}待分配数量: ${d_num}",
            textAlign: TextAlign.start,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        )
      ],
    );
  }

  // 构建底部按钮
  Widget _buildTopButton(String title, String type, Alignment align,
      BorderRadius borderRadius, String color) {
    return Builder(builder: (BuildContext context) {
      return Align(
        alignment: align,
        child: GestureDetector(
            onTap: () {
              if (type == 'confrim') {
                _confrimData();
                return;
              }

              if (type == 'add') {
                this.showAddMaterialDialog('add', numForm: {
                  'd_num': d_num,
                  'num': parentNum,
                  'y_num': y_num
                });
              } else {
                if (!sonList.any((element) => element['selected'] == true)) {
                  Utils.showText(text: '暂未选择物资');
                  return;
                }

                var ids = [];
                sonList.forEach((element) {
                  if (element['selected'] == true) {
                    ids.add({'id': element['id'], 'num': element['num']});
                  }
                });

                var numForm = {
                  'd_num': d_num,
                  'num': parentNum,
                  'y_num': y_num
                };

                if (type == 'num') {
                  showActionMaterialDialog('num',
                      title: '批量修改数量', ids: ids, numForm: numForm);
                }

                if (type == 'remark') {
                  showActionMaterialDialog('remark',
                      title: '修改备注', ids: ids, numForm: numForm);
                }

                if (type == 'del') {
                  this.delMaterial();
                }
              }
            },
            child: Container(
              child: Text(
                title,
                style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: Utils.hexToColor('#ffffff')),
              ),
              padding: EdgeInsets.symmetric(vertical: 5, horizontal: 15),
              decoration: BoxDecoration(
                  color: Utils.hexToColor(color),
                  borderRadius: BorderRadius.all(Radius.circular(4.0))),
              margin: EdgeInsets.only(right: 10),
            )),
      );
    });
  }

  // 构建按钮
  Widget _buildPage() {
    return Container(
      color: Utils.hexToColor('#F5F6FA'),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Expanded(
              flex: 1,
              child: Refresh(
                refreshController: _refreshController,
                enablePullUp: false,
                onRefresh: _onRefresh,
                child: SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  child: SingleChildScrollView(
                    child: _buildTable(),
                  ),
                ),
              ))
        ],
      ),
    );
  }

  Widget _buildTable() {
    return DataTable(
      columns: [
        DataColumn(label: Text('序号')),
        DataColumn(label: Text('物资名称')),
        DataColumn(label: Text('数量')),
        DataColumn(label: Text('计量单位')),
        DataColumn(label: Text('子物资备注')),
        DataColumn(label: Text('子RFID')),
      ],
      rows: sonList
          .asMap()
          .keys
          .map((index) => DataRow(
              color: MaterialStateProperty.resolveWith<Color>(
                  (Set<MaterialState> states) {
                if (states.contains(MaterialState.selected))
                  return Utils.hexToColor('#FF9232');
                // Even rows will have a grey color.
                // if (index % 2 == 0) return Colors.grey.withOpacity(0.3);
                return Utils.hexToColor('#ECF3FE');
                ; // Use default value for other states and odd rows.
              }),
              cells: [
                DataCell(Text("${index + 1}")),
                DataCell(Text("${sonList[index]['name']}")),
                DataCell(Text("${sonList[index]['num']}")),
                DataCell(Text("${sonList[index]['unit']}")),
                DataCell(Text("${sonList[index]['remark']}")),
                DataCell(Text("${sonList[index]['rfid']}"))
              ],
              selected: sonList[index]['selected'],
              onSelectChanged: (selected) {
                print(selected);
                setState(() {
                  sonList[index]['selected'] = selected;
                });

                print(sonList[index]['selected']);
              }))
          .toList(),
    );
  }

  // 构建表格
  // Widget _buildTable() {
  //   return PaginatedDataTable(
  //       header: Text(
  //         // "主物资数量: ${parentNum} 已分配数量: ${y_num}待分配数量: ${d_num}",
  //         'header',
  //         textAlign: TextAlign.start,
  //         maxLines: 1,
  //         overflow: TextOverflow.ellipsis,
  //         style: TextStyle(fontSize: 28.w),
  //       ),
  //       columns: [
  //         DataColumn(label: Text('序号')),
  //         DataColumn(label: Text('物资名称')),
  //         DataColumn(label: Text('数量')),
  //         DataColumn(label: Text('计量单位')),
  //         DataColumn(label: Text('子物资备注')),
  //         DataColumn(label: Text('子RFID')),
  //       ],
  //       source: _items,
  //       rowsPerPage: per_page,
  //       availableRowsPerPage: [15, 50, 100, 500],
  //       // onRowsPerPageChanged: (v) {
  //       //   setState(() {
  //       //     per_page = v;
  //       //   });
  //       //   getList();
  //       // },

  //       onPageChanged: (page) {
  //         print('onPageChanged:$page');

  //         // setState(() {
  //         //   // currentPage = (total / (page + 1)).ceil();
  //         //   currentPage = 2;
  //         // });
  //         // print((total / (page + 1)).ceil());

  //         // getList();
  //       }
  //       );
  // }

  // 下拉刷新
  void _onRefresh() async {
    _refreshController.loadComplete();
    getList(isInit: true);

    await Future.delayed(Duration(milliseconds: 600));
    _refreshController.refreshCompleted();
  }

  // 添加物资 || 编辑物资
  Future<void> showAddMaterialDialog(String type,
      {int itemInd, Map item, Map numForm}) async {
    if (type == 'edit') {
      setState(() {
        // updateStoresId = item['id'];
        itemIndex = itemInd;
      });
    }

    showDialog(
        context: context,
        builder: (context) {
          return Dialog(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(12.w))),
              insetPadding: EdgeInsets.all(0),
              child: AddUpdateSonMaterialDialog(
                baseApi: baseApi,
                type: type,
                item: widget.arguments['item'],
                orderId: widget.arguments['id'],
                numForm: numForm,
                onSubmit: (e) {
                  print(e);
                  if (itemIndex != null) {
                    if (type == 'edit') {
                      // updateSingleMaterial(item['id']);
                    } else {
                      getList(isInit: true);
                    }
                  }
                },
              ));
        });
  }

  // 添加物资 || 编辑物资
  Future<void> showActionMaterialDialog(String type,
      {int itemInd, Map item, Map numForm, String title, List ids}) async {
    // if (type == 'edit') {
    //   setState(() {
    //     // updateStoresId = item['id'];
    //     itemIndex = itemInd;
    //   });
    // }

    showDialog(
        context: context,
        builder: (context) {
          return Dialog(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(12.w))),
              insetPadding: EdgeInsets.all(0),
              child: SonMaterialAcionDialog(
                baseApi: baseApi,
                type: type,
                item: widget.arguments['item'],
                orderId: widget.arguments['id'],
                numForm: numForm,
                title: title,
                ids: ids,
                onSubmit: (e) {
                  print(e);
                  if (itemIndex != null) {
                    if (type == 'num') {
                      // updateSingleMaterial(item['id']);
                      getList(isInit: true);
                    }

                    if (type == 'remark') {
                      getList(isInit: true);
                    }
                  }
                },
              ));
        });
  }

  Future<void> delMaterial() async {
    Utils.openAlert('确定要删除吗？', context).then((confirm) {
      if (confirm) {
        var ids = [];
        sonList.forEach((element) {
          if (element['selected'] == true) {
            ids.add(element['id']);
          }
        });
        DioUtils.request('EnterMaterialSon/del',
            context: context,
            method: 'POST',
            params: {'ids': ids}, onSuccess: (res) {
          if (res['code'] == 1) {
            setState(() {
              sonList.removeWhere((element) => element['selected'] == true);
            });
          }
          Utils.showText(text: res['msg']);
        }, onError: (err) {});

        return true;
      } else {
        return false;
      }
    });
  }

  // 渲染视图
  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);

    return Scaffold(
      appBar: TopBar(
        title: '子物资',
        // actions: <Widget>[
        //   InkWell(
        //     onTap: () {
        //       for (int i = 0; i < selectList.length; i++) {
        //         setState(() {
        //           selectList[i]['selected'] = !isSelectedAll;
        //         });
        //       }

        //       setState(() {
        //         isSelectedAll = !isSelectedAll;
        //       });
        //     },
        //     child: Container(
        //       alignment: Alignment.center,
        //       height: double.infinity,
        //       padding: EdgeInsets.symmetric(horizontal: 31.w),
        //       child: Text('全选'),
        //     ),
        //   )
        // ],
      ),
      body: SafeArea(
        child: Container(
          child: Column(
            children: <Widget>[
              _buildTopButtons(),
              Expanded(
                  child: sonList.length <= 0
                      ? EmptyTips(
                          refreshController: _refreshController,
                          onRefresh: _onRefresh,
                        )
                      : _buildPage())
            ],
          ),
        ),
      ),
    );
  }
}

// 分页
class ItemDataSource extends DataTableSource {
  ItemDataSource(this.list);
  // final List list;
  final List list;

  @override
  void didUpdateWidget(ItemDataSource oldWidget) {
    // super.didUpdateWidget(oldWidget);
    print(oldWidget);
  }

  // int _selectedCount = list.length;
  @override
  int get rowCount => list.length;

  @override
  bool get isRowCountApproximate => true; // 如果不确定行的数量返回true

  @override
  int get selectedRowCount => 0;

  @override
  DataRow getRow(int index) {
    if (index >= list.length) {
      return null;
    }

    return DataRow.byIndex(
        index: index,
        // 添加选框
        selected: list[index]['selected'],
        onSelectChanged: (selected) {
          // list[index]['selected'] = selected;
          // list.add({
          //   'name': 'ni',
          //   'num': '1',
          //   'unit': 1,
          //   'remark': 'sss',
          //   'rfid': '111',
          //   'selected': false
          // });
          notifyListeners();
        },
        cells: [
          DataCell(Text('${index + 1}')),
          DataCell(Text('${list[index]['name']}')),
          DataCell(Text('${list[index]['num']}')),
          DataCell(Text('${list[index]['unit']}')),
          DataCell(Text('${list[index]['remark']}')),
          DataCell(Text('${list[index]['rfid']}'))
        ]);
  }
}

class _MyMaterialStateColor extends MaterialStateColor {
  _MyMaterialStateColor(int defaultValue, {this.isSelected})
      : super(defaultValue);
  bool isSelected;

  @override
  Color resolve(Set<MaterialState> states) {
    print(states);
    if (isSelected) {
      return Colors.red;
    }
    return Colors.amber;
  }
}
